package vip.xiaonuo.facedoor.modular.appversion.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.facedoor.modular.appversion.entity.AppVersion;
import vip.xiaonuo.facedoor.modular.appversion.mapper.AppVersionMapper;
import vip.xiaonuo.facedoor.modular.appversion.param.AppUpdateQuery;
import vip.xiaonuo.facedoor.modular.appversion.vo.AppUpdateVo;
import vip.xiaonuo.sys.modular.file.entity.SysFileInfo;
import vip.xiaonuo.sys.modular.file.service.SysFileInfoService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class AppUpdateService {

    @Value("${server.port}")
    private int port;

    @Resource
    private AppVersionService appVersionService;

    @Resource
    private SysFileInfoService fileInfoService;

    @Resource
    private AppVersionMapper versionMapper;

    public AppUpdateVo checkUpdate(AppUpdateQuery update){
        int platform = update.getPlatform();
        String version = update.getVersion();

        int versionParts = version.split("\\.").length;

        List<Integer> parts = new ArrayList<>();
        for(int i = 1 ; i <= versionParts ; i++){
            parts.add(i);
        }

        Long id = versionMapper.checkUpdate(platform,version,parts);
        AppUpdateVo result = new AppUpdateVo();
        if(id!=null){
            result.setUpToDate(false);
            AppVersion upToDateVersion = appVersionService.getById(id);
            result.setVersion(upToDateVersion.getVersion());
            result.setDescription(upToDateVersion.getDescription());
            String host = ConstantContextHolder.getSysConfig("CURRENT_IMAGE_IP", String.class, true);
            SysFileInfo file = fileInfoService.getById(upToDateVersion.getApkFile());
            if(file!=null){
                result.setFileName(file.getFileOriginName());
                result.setDownloadUrl("http://"+host+":"+port+"/sysFileInfo/download?id="+upToDateVersion.getApkFile());
            }else{
                result.setFileName("更新包已丢失");
            }
        }else{
            result.setUpToDate(true);
        }
        return result;
    }

    public static void main(String[] args) {
        String version = "1.0.01";

        int versionParts = version.split("\\.").length;
        System.out.println("versionParts = " + versionParts);
    }

}
